package com.jack006.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.jack006.api.service.BaseService;
import com.jack006.enums.UserStatus;
import com.jack006.exception.GraceException;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.AppUser;
import com.jack006.user.mapper.AppUserMapper;
import com.jack006.user.service.AppUserMngService;
import com.jack006.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @Classname AppUserMngServiceImpl
 * @Description 管理员用户列表接口实现
 * @Date 2021-07-03 15:58
 * @Created by jack
 */
@Service
public class AppUserMngServiceImpl extends BaseService implements AppUserMngService {

    @Autowired
    private AppUserMapper appUserMapper;

    @Override
    public PagedGridResult queryAllUserList(String nicename, Integer status, Date startDate, Date endDate, Integer page, Integer pageSize) {

        Example example = new Example(AppUser.class);
        example.orderBy("createdTime").desc();
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(nicename)) {
            criteria.andLike("nickname", "%" + nicename + "%");
        }

        if (UserStatus.isUserStatusValid(status)) {
            criteria.andEqualTo("activeStatus", status);
        }

        if (startDate != null) {
            criteria.andGreaterThanOrEqualTo("createdTime",startDate);
        }

        if (endDate != null) {
            criteria.andLessThanOrEqualTo("createdTime",endDate);
        }

        PageHelper.startPage(page,pageSize);
        List<AppUser> appUsers = appUserMapper.selectByExample(example);
        PagedGridResult gridResult = setterPagedGrid(appUsers, page);
        return gridResult;
    }

    @Transactional
    @Override
    public void freezeUserOrNot(String userId, Integer doStatus) {
        AppUser appUser = new AppUser();
        appUser.setId(userId);
        appUser.setActiveStatus(doStatus);
        int result = appUserMapper.updateByPrimaryKeySelective(appUser);
        if (result != 1) {
            GraceException.display(ResponseStatusEnum.SYSTEM_OPERATION_ERROR);
        }

    }
}
